import 'package:family_expense/features/system_setting/services/app_release_log_service.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class ChangeLog extends StatefulWidget {
  const ChangeLog({super.key});

  @override
  State<ChangeLog> createState() => _ChangeLogState();
}

class _ChangeLogState extends State<ChangeLog> {
  final int _pageSize = GeneralConfig.listViewPageSize;

  String? _appVersion;

  @override
  void initState() {
    super.initState();

    _getAppVersion();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('更新日志')),
      body: _buildBody(),
    );
  }

  /// Builds main body.
  Widget _buildBody() {
    final appReleaseLogService = AppReleaseLogService();

    return PagingListView(
      padding: const EdgeInsets.only(top: 10.0),
      pageSize: _pageSize,
      retrieveData: (pageIndex) =>
          appReleaseLogService.listChangeLog(_pageSize, pageIndex!),
      itemBuilder: (context, entry, index) => _buildCard(context, entry),
    );
  }

  /// Builds the list of widget to display the card with multi-line change log items.
  Widget _buildCard(BuildContext context, AppInfo appInfo) {
    final cardChildren = <Widget>[
      Row(
        children: [
          Text(
            '${appInfo.appVersion} @ ${appInfo.releaseDate.formatDate(DatePatterns.longDate)}',
            style: const TextStyle(fontSize: 18.0),
          ),
          const SizedBox(width: 10.0),
          if (_appVersion == appInfo.appVersion)
            Chip(
              padding: const EdgeInsets.all(0.0),
              label: const Text('我的版本'),
              backgroundColor: Colors.blue[100],
            ),
        ],
      ),
      const Divider(),
    ];

    cardChildren.addAll(
      appInfo.changeLog!
          .split('\\n')
          .map(
            (p) => Container(
              margin: const EdgeInsets.only(bottom: 4.0),
              child: Text(p),
            ),
          ),
    );

    return Card(
      elevation: 6.0,
      margin: const EdgeInsets.all(10.0),
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: cardChildren,
        ),
      ),
    );
  }

  Future<void> _getAppVersion() async {
    // Gets app current version.
    final appVersion = await getAppLocalVersion();

    // Triggers the build.
    if (mounted) {
      setState(() => _appVersion = appVersion);
    }
  }
}
